package net.pws.oos.biz.query.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.pws.common.util.StringUtils;
import net.pws.common.persistence.Page;
import net.pws.common.persistence.QueryRepository;
import net.pws.oos.biz.model.Organization;
import net.pws.oos.biz.model.Phone;
import net.pws.oos.biz.query.PhoneQuery;
import net.pws.oos.biz.query.parameter.PhoneQueryParameter;

import org.springframework.stereotype.Service;

@Service(value = "phoneQuery")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DefaultPhoneQuery extends AbstractFinder implements PhoneQuery {

	@Override
	public Phone get(String userId, String imei, String imsi) {
		String hql = "from Phone where userId=? and imei=? and imsi=?";
		return (Phone) entityManager.findFirst(hql, new Object[] { userId,
				imei, imsi });
	}

	@Override
	public List<Phone> list(String userId) {
		String hql = "from Phone where userId=? order by loginTime desc";
		return entityManager.findList(hql, new Object[] { userId });
	}

	@Override
	public List<Map> list(PhoneQueryParameter parameter) {
		StringBuilder countSql = new StringBuilder(QueryRepository
				.getInstance().get("sql.countPhone"));
		StringBuilder sql = new StringBuilder(QueryRepository.getInstance()
				.get("sql.listPhone"));
		List<Object> params = new ArrayList<Object>();
		buildQuery(sql, countSql, params, parameter);
		sql.append(" group by p.user_id order by phoneCount desc");

		Page page = (Page) entityManager.nativeFindPage(countSql.toString(),
				sql.toString(), params.toArray(), parameter.getStart(),
				parameter.getLimit());
		return page.getData();
	}

	@Override
	public int count(PhoneQueryParameter parameter) {
		StringBuilder sql = new StringBuilder(QueryRepository.getInstance()
				.get("sql.countPhone"));
		List<Object> params = new ArrayList<Object>();
		buildQuery(sql, null, params, parameter);
		Map map = (Map) entityManager.nativeFindFirst(sql.toString(),
				params.toArray());
		return ((Number) map.get("recordCount")).intValue();
	}

	private void buildQuery(StringBuilder sql, StringBuilder sql2,
			List<Object> params, PhoneQueryParameter parameter) {
		if (sql2 == null) {
			sql2 = new StringBuilder();
		}
		if (StringUtils.isNotBlank(parameter.getUserId())) {
			sql.append("and u.id=? ");
			sql2.append("and u.id=? ");
			params.add(parameter.getUserId());
		}
		if (StringUtils.isNotBlank(parameter.getOrganId())) {
			Organization org = entityManager.find(Organization.class,
					parameter.getOrganId());
			if (org != null) {
				sql.append(" and o.inner_code like ?");
				sql2.append(" and o.inner_code like ?");
				params.add(org.getInnerCode() + "%");
			}
		}
	}

}
